package com.laikan.reader.bookreader.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.util.ChapterDown;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.BookChapterAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.bean.ChapterDetailBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.*;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.warm.WarmWindow;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wx 书籍目录页
 */
public class BookChapter extends BasicActivity {

    // 目录列表数据组
    private TextView title_tv;
    private LinearLayout load_btn;
    private BookChapterAdapter mAdapter;
    private ArrayList<ChapterBean> mData;
    //章节数据
    private ArrayList<ChapterBean> chapterData;
    private String book_id = "";
    private String bookname = "";
    private String writername = "";
    private String groupId = "";
    private TextView load_all_btn, common_prompt_content, common_refresh_net;
    private String state = "";
    private ListView chapter_list;
    private MsgReceiver msgReceiver;
    private ImageView back_tv;
    private Drawable drawable_back_tv;
    private RelativeLayout back_layout, common_loaddata_notice;
    private Book bookDes;
    private Bundle bundle;
    private int folderCount = 0;
    private int downFocu = 0;
    private LoadingDialog mLoadingDialog;
    private WarmWindow log;
    private long mLoadDelayInternalTime;
    private int mListCurrentPosition = -1;
    private int mRequestDataType = -1;
    // 开始下载
    private int StartDownload = 1;
    // 下载中
    private int DownloadCompleting = 2;
    // 下载完成
    private int DownloadComplete = 3;

    private CircleProgressBar circleProgressBar;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == StartDownload) {
                ToastMgr.showShortToast("开始下载");
            }else if (msg.what == DownloadCompleting) {
                folderCount++;
                load_all_btn.setText("已下载: " + folderCount);
            }else if (msg.what == DownloadComplete) {
                mAdapter.notifyDataSetChanged();
                ToastMgr.showShortToast("下载完成");
            }
        }
    };
    private boolean clientable = true;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_book_chapter);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        chapter_list = (ListView)findViewById(R.id.chapters_list);
        load_btn = (LinearLayout)findViewById(R.id.load_btn);
        title_tv = (TextView)findViewById(R.id.tv_title);
        load_all_btn = (TextView)findViewById(R.id.load_all_btn);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
    }

    @Override
    protected void initData() {
        mLoadingDialog = new LoadingDialog(mContext);
        log = new WarmWindow();
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        state = getIntent().getStringExtra("state");
        bookname = getIntent().getStringExtra("bookName");
        book_id = getIntent().getStringExtra("book_id");
        writername = getIntent().getStringExtra("writername");
        groupId = getIntent().getStringExtra("groupId");
        title_tv.setText(bookname);
        // 注册广播，显示下载进度
        System.out.println(book_id);
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(book_id + Constants.CHAPTER_DOWN_BROADCAST);
        registerReceiver(msgReceiver, intentFilter);
        // 获取书籍详情
        bookDes = (Book)getIntent().getSerializableExtra("bookDes");
        mData = new ArrayList<>();
        mAdapter = new BookChapterAdapter(mContext, mData, book_id);
        chapterData = new ArrayList<>();
        readFile();
        chapter_list.setAdapter(mAdapter);
        int pos1 = SPUtil.getInt(book_id + "chaptep_rec", 0);
        if (pos1 < 0) {
            pos1 = 0;
        }
        if (pos1 > chapterData.size()) {
            pos1 = chapterData.size() - 1;
        }

        if (pos1 != 0 && pos1 > 0) {
            chapter_list.setSelection(getAllPos(chapterData.get(pos1 - 1).getId()));
        }

    }

    /**
     * 获取章节id对应目录的下标
     *
     * @param chapterId
     *
     * @return
     */
    private int getPos(String chapterId) {
        for (int i = 0; i < chapterData.size(); i++) {
            if (chapterId.equals(chapterData.get(i).getId())) {
                return i;
            }
        }
        return 0;
    }

    private int getAllPos(String chapterId) {
        for (int i = 0; i < mData.size(); i++) {
            if (chapterId.equals(mData.get(i).getId())) {
                return i;
            }
        }
        return 0;
    }

    @Override
    protected void onDestroy() {
        // 注销广播
        unregisterReceiver(msgReceiver);
        KLog.e("----------------bookChapter  onDestroy!");
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        clientable = true;
        MobclickAgent.onResume(this);
        if (SPUtil.getInt(book_id + mData.get(downFocu).getId() + "buyback", 3) == 0) {
            goChapterBackZero(downFocu);
            SPUtil.putInt(book_id + mData.get(downFocu).getId() + "buyback", 3);
        }else if (SPUtil.getInt(book_id + mData.get(downFocu).getId() + "buyback", 3) == 1) {
            goChapterBack(downFocu);
            SPUtil.putInt(book_id + mData.get(downFocu).getId() + "buyback", 3);
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 取得本地文件中存储 目录列表的 json 数据
     */
    private void readFile() {
        try {
            BaseDataBean<BaseListDataBean<ChapterBean>> data;
            Gson gson = new Gson();
            File file = PublicUtil.getRootPath();
            String json = FileUtil.readFileString(file.getPath() + "/LaikanReader/book/" + book_id + "/chapter");
            Type type = new TypeToken<BaseDataBean<BaseListDataBean<ChapterBean>>>() {
            }.getType();
            data = gson.fromJson(json, type);

            mData = data.getData().getData();
            mAdapter.setDatas(mData);

            for (int i = 0; i < mData.size(); i++) {
                if (!mData.get(i).isVolume()) {
                    chapterData.add(mData.get(i));
                }
            }
        }catch (Exception e) {
        }
    }

    @Override
    protected void setListener() {
        load_btn.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        load_all_btn.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        chapter_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//                mListCurrentPosition = arg2;
                // 通过 isvolume 过滤 掉 目录列表中的 卷，“卷” 不可点击
                if (clientable &&!mData.get(arg2).isVolume()) {
                    downFocu = arg2;
                    File file = PublicUtil.getRootPath();
                    file = new File(file.getPath() + "/LaikanReader/book/" + book_id + "/" + mData.get(arg2).getId());
                    // 1 表示从书籍详情进入 目录页的
                    if (Constants.RESULT_OK.equals(state)) {
//                        if(ActivityUitl.isNetworkAvailable(BookChapter.this)){
//                            mRequestDataType = 0;
                            if(file.exists()){
                                goChapterBackZero(arg2);
                                clientable = false;
                            }else{
                                getData(arg2, 0);
                            }
//                        }else {
//                            common_prompt_content.setText(R.string.laikan_network_anomaly);
//                            switchPageStatus(false);
//                        }


                    }else {
                        // 从阅读页进入 目录页的
                        int pos1 = SPUtil.getInt(book_id + "chaptep_rec", 0);
                        int pos2 = getPos(mData.get(arg2).getId());
                        if (pos1 == pos2) {
                            SPUtil.putInt(book_id + "recCurPage", 0);
                            finish();
                        }else {
                            if (file.exists()) { // 从本地读取数据
                                goChapterBack(arg2);
                                clientable = false;
                            }else {
//                                if(ActivityUitl.isNetworkAvailable(BookChapter.this)){
//                                    mRequestDataType = 1;
                                    getData(arg2, 1);
//                                }else {
//                                    common_prompt_content.setText(R.string.laikan_network_anomaly);
//                                    switchPageStatus(false);
//                                }

                            }
                        }

                    }
                }
            }
        });
    }

    /**
     * 阅读页进章节目录页
     *
     * @param index
     */
    private void goChapterBack(int index) {
        SPUtil.putInt(book_id + "recCurPage", 0);
        SPUtil.putInt(book_id + "recCurPage", 0);
        SPUtil.putInt(book_id + "chaptep_rec", getPos(mData.get(index).getId()));
        //        Intent intent = new Intent();
        //        intent.putExtra("isResOpenDoc", true);
        //        intent.putExtra("groupId", groupId);
        //        bundle = new Bundle();
        //        bundle.putSerializable("bookDesaaa", mData);
        //        intent.putExtras(bundle);
        //        intent.setClass(mContext, ReaderDetailActivity.class);
        //        setResult(1234, intent);
        readerPageChapterRefreshEvent();
        finish();
    }

    private void readerPageChapterRefreshEvent() {
        LaiKanEvent laiKanEvent = LaiKanEvent.getInstance();
        laiKanEvent.setEventID(LaiKanEvent.EVENT_ID_READERDETAIL_CHAPTER_REFRESH);
        HashMap map = new HashMap();
        map.put("chapterData", mData);
        map.put("isResOpenDoc", true);
        laiKanEvent.setEventMap(map);
        BasicApplication.postEvent(laiKanEvent);
    }
    /**
     * 详情页进阅读页
     *
     * @param index
     */
    private synchronized void goChapterBackZero(int index) {
        int pos1 = SPUtil.getInt(book_id + "chaptep_rec", 0);
        int pos2 = getPos(mData.get(index).getId());
        if (pos1 != pos2) {
            SPUtil.putInt(book_id + "recCurPage", 0);
        }
        SPUtil.putInt(book_id + "recCurPage", 0);
        SPUtil.putInt(book_id + "chaptep_rec", getPos(mData.get(index).getId()));
        Intent intent = new Intent();
        intent.setClass(mContext, ReaderDetailActivity.class);
        SPUtil.putString("chapid_" + book_id, mData.get(index).getId() + "");
        SPUtil.putInt("chapterCount_pos_" + mData.get(index).getId(), 1);
        intent.putExtra("bookId", book_id);
        intent.putExtra("chapterid", mData.get(index).getId());
        intent.putExtra("bookName", bookname);
        intent.putExtra("writername", writername);
        intent.putExtra("groupId", groupId);
        //        intent.putExtra("chapmulu", chapterData);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (DBBook.getInstance().queryBookById(book_id) != null) {
            intent.putExtra("flag", "");
        }else {
            intent.putExtra("flag", "book_des");
        }

        //-----------------改-补全Book对象的sortIndex信息以便更新书架----------------
        Book book = DBBook.getInstance().queryBookById(book_id);
        if (null != book){
            double sortIndex = book.getSortIndex();
            bookDes.setSortIndex(sortIndex);
        }
        //------------------------

        // 传递书籍详情信息
        bundle = new Bundle();
        bundle.putSerializable("bookDes", bookDes);
        intent.putExtras(bundle);
        startActivity(intent);
        dismissDialog();
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.load_all_btn:

                if (!ActivityUitl.isNetworkAvailable(mContext)) {
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                    return;
                }
                if (SPUtil.getBoolean(book_id + "isDowning_chapter", true)) {

                    SPUtil.putBoolean(book_id + "isDowning_chapter", false);
                    handler.sendEmptyMessage(StartDownload);
                    final ChapterDown chapterDown = new ChapterDown(mContext, book_id, bookname, chapterData);
                    new Thread() {
                        @Override
                        public void run() {
                            chapterDown.downloadChapter();
                        }
                    }.start();
                    // 添加到书架
                    DBBook.getInstance().insertBook(bookDes);
                }else {
                    ToastMgr.showShortToast("正在下载中...");
                }

                break;
            case R.id.back_layout:
                // 返回
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.common_refresh_net:
                mLoadDelayInternalTime = System.currentTimeMillis() + 2000;
                circleProgressBar.setVisibility(View.VISIBLE);
                if(ActivityUitl.isNetworkAvailable(BookChapter.this)){
                    getData(mListCurrentPosition, mRequestDataType);
                }else {
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            default:
                break;
        }
    }

    // 返回键时 指向 返回位置
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED);

        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 保存章节
     *
     * @param chapterid
     * @param json
     */
    private void saveChapterFile(final String chapterid, String json) {
        String SKEY = "123456789012345678901234567890123456789088888888";
        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + "/LaikanReader/book/" + book_id + "/" + chapterid);
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        EncryptUtils.encrypt(new File(file.getPath()), SKEY, json);
        handler.sendEmptyMessage(DownloadCompleting);
    }

    /**
     * 获取已下载章节id
     *
     * @param file
     *
     * @return
     */
    public List<String> getFile(File file) {
        List<String> mFileList = new ArrayList<String>();
        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                if (f.isFile()) {
                    mFileList.add(f.getName());
                }else {
                    getFile(f);
                }
            }
        }catch (Exception e) {
            // TODO: handle exception
        }

        return mFileList;
    }

    /**
     * 访问网络 获取章节数据
     */
    private void getData(final int chapterIdIndex, final int goType) {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<ChapterDetailBean> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<ChapterDetailBean>>() {
                }.getType();
                result = gson.fromJson(httpResponse.responseContent, type);
                try {
                    if (result != null) {
//                        switchPageStatus(true);
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {

                            if ("601".equals(result.getError_no()) || "602".equals(result.getError_no())) {
                                if (SystemUtil.isLogin()) {
                                    bulkPurchase(chapterIdIndex, goType);
                                }else {
                                    log.showPickDialog(mContext);
                                }
                            }
                        }else {
                            if (goType == 0) {
                                goChapterBackZero(chapterIdIndex);
                            }else {
                                goChapterBack(chapterIdIndex);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                        finish();
                    }
                }catch (Exception e) {
                    SnackBarNotice.customSnackbarShow(back_layout, R.string.laikan_data_load_failed);
//                    common_prompt_content.setText(R.string.laikan_data_load_failed);
//                    closeDelayLoading(System.currentTimeMillis());
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
//                common_prompt_content.setText(R.string.laikan_data_load_failed);
//                closeDelayLoading(System.currentTimeMillis());
                SnackBarNotice.customSnackbarShow(back_layout, R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_detail + book_id + "_" + mData.get(chapterIdIndex).getId());
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail + book_id + "_" + mData.get(chapterIdIndex).getId(), map, null, null, requestListener);
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelayInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    switchPageStatus(false);
                }
            }, 1000);
        }else {
            switchPageStatus(false);
        }
    }

    private void switchPageStatus(boolean isSucess) {
        if (isSucess) {
            load_btn.setVisibility(View.VISIBLE);
            chapter_list.setVisibility(View.VISIBLE);
            common_loaddata_notice.setVisibility(View.GONE);
            circleProgressBar.setVisibility(View.INVISIBLE);
        }else {
            load_btn.setVisibility(View.GONE);
            chapter_list.setVisibility(View.GONE);
            common_loaddata_notice.setVisibility(View.VISIBLE);
            circleProgressBar.setVisibility(View.INVISIBLE);
        }
    }


    /**
     * 批量购买
     * boo 通知是否刷新页面
     *
     * @date 2015-11-20 下午2:33:53
     */
    private void bulkPurchase(int arg2, int goInType) {
        if ("3".equals(groupId)) {

            getQuanbenPrice(mData.get(arg2).getId(), goInType);
            // 出版物
        }else {
            // 非出版物
            Intent intent = new Intent();
            // 批量购买修改
            intent.setClass(this, DesChapterBuy.class);
            intent.putExtra("book_id", book_id);
            intent.putExtra("bookName", bookname);
            intent.putExtra("state", "1");
            intent.putExtra("notiPage", true);
            intent.putExtra("isVis", true);
            intent.putExtra("goInType", goInType);
            intent.putExtra("writername", writername);
            intent.putExtra("writername", writername);
            intent.putExtra("startChapeterID", mData.get(arg2).getId());
            // 传递书籍详情信息
            Bundle bundle = new Bundle();
            bundle.putSerializable("bookDes", bookDes);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    String chap_money = "";

    /**
     * 获取全本价格
     */
    private void getQuanbenPrice(final String chapterid1, final int goInType) {
        mLoadingDialog.show();
        chap_money = "";
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("bookId", book_id);
        map.put("chapterId", 1 + ""); // 查看章节价格,如果是图书那么章节可以传一个任意大于零的整数。
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mLoadingDialog.dismiss();
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    //                    obj.getJSONObject("data").getString("price");
                    String error_msg = obj.getString("error_msg");
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        chap_money = obj.getJSONObject("data").getString("price");
                        Intent intent = new Intent(BookChapter.this, DesBookBuy.class);
                        intent.putExtra("bookName", bookname);
                        intent.putExtra("bookId", book_id);
                        intent.putExtra("realPrice", chap_money);
                        intent.putExtra("writername", writername);
                        intent.putExtra("chid", mData.get(downFocu).getId());
                        intent.putExtra("goInType", goInType);
                        intent.putExtra("isFollow", DBBook.getInstance().queryBookById(book_id) != null);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("bookDes", bookDes);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 101);
                    }else {
                        ToastMgr.showShortToast(error_msg);
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mLoadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookchapter_getQuanbenPrice + book_id + "_" + chapterid1);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

        // 90接口,查看章节价格
//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_bookchapter_getQuanbenPrice + book_id + "_" + chapterid1, map, null, null, requestListener);
    }

    /**
     * 广播接收器
     *
     * @author len
     */
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 拿到进度，更新UI
            int progress = intent.getIntExtra("progress", 0);
            KLog.i("progress::"+ progress);
            load_all_btn.setText("已下载" + progress);

        }

    }

}
